<?php

namespace App\Kuafu\Product\Service;

use App\Kuafu\Category\Model\CategoryModel;
use App\Kuafu\Category\Service\CategoryService;
use App\Kuafu\Product\Enum\CodeEnum;
use App\Kuafu\Product\Enum\ProductCacheEnum;
use App\Kuafu\Product\Enum\ProductCodeEnum;
use App\Kuafu\Product\Exceptions\ProductException;
use App\Kuafu\Product\Model\PackageProductMapping;
use App\Kuafu\Product\Model\Product;
use App\Kuafu\User\Service\AuthService;
use Illuminate\Support\Facades\Cache;
use App\Kuafu\Base\Service\BaseService;
use Illuminate\Support\Facades\DB;

class PackageProductService extends BaseService
{
    /**
     * 新增套餐
     * @param $productList
     * @param $menuId
     * @throws ProductException
     */
    public static function batchAddPackAgeProduct($productList, $menuId)
    {
        //过滤套餐商品id
        $filterPackageIds = self::filterPackageIds($productList);
        //查询套餐商品数据
        if (!empty($filterPackageIds)) {
            $menuIdFirst = 0;
            $list        = PackageProductMapping::getPackageProductListByIds($filterPackageIds, $menuIdFirst);
            foreach ($list as $value) {
                unset($value['id']);
                $value['menuId'] = $menuId;
            }
            PackageProductMapping::addPackageProduct($list->toArray());
        }
    }

    /**
     * 修改套餐
     * @param $productList
     * @param $menuId
     * @throws ProductException
     */
    public static function batchEditPackageProduct($productList, $menuId)
    {
        //删除原有菜单绑定的套餐商品
        $packageIds = self::filterPackageIds($productList);
        PackageProductMapping::delPackageByMenuId($menuId);
        if (!empty($packageIds)) {
            $firstMenuId = 0;
            $list        = PackageProductMapping::getPackageProductListByIds($packageIds, $firstMenuId);
            foreach ($list as $value) {
                unset($value['id']);
                $value['menuId'] = $menuId;
            }
            PackageProductMapping::addPackageProduct($list->toArray());
        }
    }

    /**
     * 过滤是套餐的id集合
     * @param $productList
     * @return array
     */
    public static function filterPackageIds($productList): array
    {
        return collect($productList)->map(function ($item) {
            if (isset($item['type'])) {
                if ($item['type'] == CodeEnum::PRODUCT_TYPE_PACKAGE) {
                    return $item['productId'];
                } else {
                    return null;
                }
            } else {
                return null;
            }
        })->filter()->toArray();
    }

    public static function delPackageById($packageId, $menuId = 0)
    {
        return PackageProductMapping::query()
                                    ->where(['packageId' => $packageId, 'menuId' => $menuId])
                                    ->delete();
    }
}
